//
//  MYGPatientAddViewController.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/18.
//

import UIKit

class MYGPatientAddViewController: MYGBaseController {
    var patientArr:[String:[MYGPatientModel]] = [:]
    var titleArr:[String] = []
    var contentArr:[[MYGPatientModel]] = []
    var selectArr:[Int] = []
    var oldArr:[MYGPatientModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "分级诊疗"
        navigationBarShow()
        initUI()
        getDatasource()

    }
    @objc func screenAction(){
        var filteredPeople = oldArr.filter { person in
            person.name.contains(searchTextField.text ?? "")
        }
        if searchTextField.text == ""{
            filteredPeople = oldArr
        }
        patientArr = [:]
        titleArr.removeAll()
        contentArr.removeAll()
        groupByInitialLetter(people: filteredPeople)
    }
    @objc func sureAction(){
        
    }
    
    private func initUI(){
        view.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(SCALEWIDTH(15))
            make.right.equalToSuperview().offset(-SCALEWIDTH(15))
            make.height.equalTo(SCALEWIDTH(35))
            make.top.equalToSuperview().offset(SCALEWIDTH(15))
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-50)
            make.top.equalTo(searchTextField.snp.bottom)
        }
        view.addSubview(addPBtn)
        addPBtn.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(tableView.snp.bottom)
        }
        view.layoutIfNeeded()
        addPBtn.addCAGradientLayerColor(colors: [RGBA(r: 73, g: 117, b: 236, a: 1).cgColor,RGBA(r: 151, g: 179, b: 255, a: 1).cgColor], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 1, y: 0))
    }
    private func getDatasource(){
        MYGNetwork<MYGHomePageAPI, MYGPageModel<MYGPatientModel>>.request(target: .getPatientList(param: [
            "type":2,
            "pageSize":"100",
            "page":"1"])) {[weak self] item in
                if item.list.count > 0{
                    self?.oldArr = item.list
                    self?.groupByInitialLetter(people: item.list)
                }
                
            } failed: { _, error in
                MMYGHUD.showToast(text: error)
            }
    }
    private lazy var searchTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(14)
        tf.textColor = .rgba(51, 51, 51)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 15
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.image(UIImage(named: "Chat/search"))
            confer.text(" 搜索")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        tf.textAlignment = .center
         tf.addTarget(self, action: #selector(screenAction), for: .editingChanged)
        //tf.delegate = self
        return tf
    }()
    lazy var tableView: UITableView = {
        let control = UITableView()
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.register(cellWithClass: MYGPatientAddTableViewCell.self)
        return control
    }()
    private lazy var addPBtn:UIButton = {
        let vi = UIButton()
        vi.setTitle("确定", for: .normal)
        vi.titleLabel?.font = .medium(17)
        vi.setTitleColor(.white, for: .normal)
        vi.addTarget(self, action: #selector(sureAction), for: .touchUpInside)
        return vi
    }()

    func transformToPinYin(str:String)->String{
        let mutableString = NSMutableString(string: str)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let string = String(mutableString)
        if str.count == 0{
            return "#"
        }
        if string.count == 0{
            let firstCharacter = str.first!
            return String(firstCharacter)
        }else{
            let firstCharacter = string.first!
            return String(firstCharacter)
        }
        // 输出：H
        
    }
    // 将数组按首字母拼音分组
    func groupByInitialLetter(people: [MYGPatientModel]){
        var grouped = [String: [MYGPatientModel]]()
        
        for person in people {
            let initialLetter = transformToPinYin(str: person.name)
            if grouped[initialLetter] == nil {
                grouped[initialLetter] = []
            }
            grouped[initialLetter]?.append(person)
        }
        var unsortedDictionary: [String: [MYGPatientModel]] = [:]
        let sortedDictionary22 = grouped.sorted(by: { $0.key < $1.key })
        for item in sortedDictionary22 {
            unsortedDictionary[item.key] = item.value
            titleArr.append(item.key)
            contentArr.append((item.value))
        }
        patientArr = unsortedDictionary
        
        tableView.reloadData()
    }
}
extension MYGPatientAddViewController:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return patientArr.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 82.5
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let vi = UIView()
        let lab = UILabel()
        lab.text = titleArr[section]
        lab.font = .regular(19)
        lab.textColor = .rgba(5, 5, 5, 1)
        vi.addSubview(lab)
        lab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.height.equalTo(20)
        }
        return vi
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let arr:[MYGPatientModel] = contentArr[section]
        return arr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGPatientAddTableViewCell.self, for: indexPath)
        let arr:[MYGPatientModel] = contentArr[indexPath.section]
        cell.modelDa = arr[indexPath.row]
        if selectArr.contains(cell.modelDa.id){
            cell.selectBtn.isSelected = true
        }else{
            cell.selectBtn.isSelected = false
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let arr:[MYGPatientModel] = contentArr[indexPath.section]
        let model = arr[indexPath.row]
        
        if selectArr.contains(model.id) {
            for inr in 0...selectArr.count - 1 {
                if model.id == selectArr[inr]{
                    selectArr.remove(at: inr)
                }
            }
        }else{
            selectArr.append(model.id)
        }
        tableView.reloadData()
    }
}
